package cn.zhuoluodada.opensource.smartdb.datasource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 读写分离的数据源，默认读数据库使用轮询策略
 *
 * @author zhuoluodada@qq.com
 */
public class MasterSlaveDataSourceGroup implements SmartDbDataSourceGroup {

    protected static Logger LOG = LoggerFactory.getLogger(MasterSlaveDataSourceGroup.class);

    private SmartDbDataSource master;
    private SmartDbDataSource[] slave;
    private AtomicInteger roundIndex = new AtomicInteger(-1);

    public MasterSlaveDataSourceGroup(SmartDbDataSource master, SmartDbDataSource[] slave) {
        this.master = master;
        this.slave = slave;
    }

    @Override
    public Connection getConnection(OptEnum opt) throws SQLException {
        switch (opt) {
            case WRITE:
                return master.getConnection();
            case READ:
                int round = roundIndex.incrementAndGet();
                return slave[Math.abs(round % slave.length)].getConnection();
                default:
        }
        throw new SQLException("cannot find OptEnum");
    }

    @Override
    public void releaseConnection(OptEnum opt, Connection connection) {
        switch (opt) {
            case WRITE:
                master.releaseConnection(connection);
                break;
            case READ:
                try {
                    if(connection != null){
                        connection.close();
                    }
                } catch (SQLException e) {
                    LOG.error("cannot releaseConnection Connection", e);
                }
                break;
            default:
        }
    }

    @Override
    public void close() throws IOException {

    }
}
